﻿using System;
using System.Diagnostics;
using System.Web;

namespace Morus.Presentation
{
    public abstract class HttpHandlerView : IHttpHandler, IView
    {
        private readonly bool _throwExceptionIfNoPresenterBound;

        protected HttpHandlerView()
            : this(true)
        {
        }

        protected HttpHandlerView(bool throwExceptionIfNoPresenterBound)
        {
            _throwExceptionIfNoPresenterBound = throwExceptionIfNoPresenterBound;
        }

        public bool ThrowExceptionIfNoPresenterBound
        {
            [DebuggerStepThrough]
            get
            {
                return _throwExceptionIfNoPresenterBound;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            var presenterBinder = new PresenterBinder(this);
            presenterBinder.PerformBinding();

            OnLoad();

            presenterBinder.Release();
        }

        public virtual bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public event EventHandler Load;

        protected virtual void OnLoad()
        {
            if (Load != null)
            {
                Load(this, EventArgs.Empty);
            }
        }
    }
}